package org.scau.studentevaluation.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.usermodel.*;
import org.scau.studentevaluation.config.global.log.WebLog;
import org.scau.studentevaluation.entity.dos.RulesDO;
import org.scau.studentevaluation.entity.dos.Table;
import org.scau.studentevaluation.entity.dtos.RuleDTO;
import org.scau.studentevaluation.entity.query.RuleQuery;
import org.scau.studentevaluation.entity.response.Result;
import org.scau.studentevaluation.exception.FieldNullException;
import org.scau.studentevaluation.service.CollegeI;
import org.scau.studentevaluation.service.RulesServiece;
import org.scau.studentevaluation.util.ResultUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@RestController
@Slf4j
@Api("Rules控制器")
public class RulesController {
    @Autowired
    private RulesServiece rulesServiece;
    @Autowired
    private CollegeI collegeI;

    /**
     *
     * @param college 字符串，学院名称
     * @return 获取该学院本学期的所有规则
     */
    @GetMapping("/rules")
    @ApiOperation("获取规则rules")
    @WebLog
    public Result getRules(String college){
        return ResultUtil.success("访问rules接口GET方法，参数是"+college,rulesServiece.getRules(college));
    }

    /**
     *
     * @param dtos 列表，对应前端解析后的数据格式
     *
     * @return
     */
    @PostMapping("/rules")
    @ApiOperation("上传规则rules")
    @WebLog
    public Result uploadRelus(@RequestBody List<RuleDTO> dtos){
        // 将dto转换成do，不影响service接口参数
        List<RulesDO> rules = new ArrayList<>();
        dtos.forEach(dto->rules.add(dto.converToDO(dto)));
        return ResultUtil.success("访问rules接口POST，参数是"+rules,rulesServiece.uploadRules(rules));
    }

    /**
     *
     * @param query 查询参数
     *              实例：
     * {
     *   "subject": 【德智体标识：数字in(0:2)】,
     *   "reluIndex": 大条（德智体之一）下的第几条：数字】,
     *   "college": 【学院名：字符串】,
     *   "reluYear": 【年份：数字：default（本学年）】
     * }
     * @return
     * @throws FieldNullException 缺少关键参数
     */
    @PostMapping("/detail")
    @ApiOperation("具体规则")
    @WebLog
    public Result getdetailRule(@RequestBody RuleQuery query) throws FieldNullException {
        return ResultUtil.success("访问rules接口POST，参数是"+query,rulesServiece.getDetailRule(query));
    }

    /**
     * Excel表格导出接口
     * http://localhost:8080/ExcelDownload
     * @param response response对象
     * @throws IOException 抛IO异常
     */
    @RequestMapping("/download")
    public void excelDownload(String college, HttpServletResponse response) throws IOException {
        //获取学院
        System.out.println(college);
        //获取排序好的结果
        List<Table> tables = collegeI.getTable(college);


        //表头数据
        String[] header = {"学号", "姓名", "德育分", "智育分", "体育分", "总分"};
        //数据内容
        String[] student1 = {"1", "小红", "女", "23", "成都青羊区", "96"};
        String[] student2 = {"2", "小强", "男", "26", "成都金牛区", "91"};
        String[] student3 = {"3", "小明", "男", "28", "成都武侯区", "90"};

        //声明一个工作簿
        HSSFWorkbook workbook = new HSSFWorkbook();

        //生成一个表格，设置表格名称为"学生表"
        HSSFSheet sheet = workbook.createSheet("综测年度结果");

        //设置表格列宽度为10个字节
        sheet.setDefaultColumnWidth((short) 10);

        //创建第一行表头
        HSSFRow headrow = sheet.createRow(0);

        //遍历添加表头(下面模拟遍历学生，也是同样的操作过程)
        for (int i = 0; i < header.length; i++) {
            //创建一个单元格
            HSSFCell cell = headrow.createCell((short) i);

            //创建一个内容对象
            HSSFRichTextString text = new HSSFRichTextString(header[i]);

            //将内容对象的文字内容写入到单元格中
            cell.setCellValue(text);
        }

        //模拟遍历结果集，把内容加入表格
        //模拟遍历第一个学生
        for (int i = 1;i<=tables.size();i++){
            //一行行的添加数据
            HSSFRow row = sheet.createRow(i); //创建行
            long number = tables.get(i-1).getId();
            String name =  tables.get(i-1).getName();
            float sum = tables.get(i-1).getSum();
            float de = tables.get(i-1).getDe();
            float zhi = tables.get(i-1).getZhi();
            float ti = tables.get(i-1).getTi();

            HSSFCell cell = row.createCell((short) 0);
            HSSFRichTextString text = new HSSFRichTextString(String.valueOf(number));
            cell.setCellValue(text);

            cell = row.createCell((short) 1);
            text = new HSSFRichTextString(String.valueOf(name));
            cell.setCellValue(text);

            cell = row.createCell((short) 2);
            text = new HSSFRichTextString(String.valueOf(de));
            cell.setCellValue(text);

            cell = row.createCell((short) 3);
            text = new HSSFRichTextString(String.valueOf(zhi));
            cell.setCellValue(text);

            cell = row.createCell((short) 4);
            text = new HSSFRichTextString(String.valueOf(ti));
            cell.setCellValue(text);

            cell = row.createCell((short) 5);
            text = new HSSFRichTextString(String.valueOf(sum));
            cell.setCellValue(text);




        }

//        HSSFRow row1 = sheet.createRow(1);
//        for (int i = 0; i < student1.length; i++) {
//            HSSFCell cell = row1.createCell(i);
//            HSSFRichTextString text = new HSSFRichTextString(student1[i]);
//            cell.setCellValue(text);
//        }
//
//        //模拟遍历第二个学生
//        HSSFRow row2 = sheet.createRow(2);
//        for (int i = 0; i < student2.length; i++) {
//            HSSFCell cell = row2.createCell(i);
//            HSSFRichTextString text = new HSSFRichTextString(student2[i]);
//            cell.setCellValue(text);
//        }
//
//        //模拟遍历第三个学生
//        HSSFRow row3 = sheet.createRow(3);
//        for (int i = 0; i < student3.length; i++) {
//            HSSFCell cell = row3.createCell(i);
//            HSSFRichTextString text = new HSSFRichTextString(student3[i]);
//            cell.setCellValue(text);
//        }

        //准备将Excel的输出流通过response输出到页面下载
        //八进制输出流
        response.setContentType("application/octet-stream");

        //这后面可以设置导出Excel的名称，此例中名为student.xls
        response.setHeader("Content-disposition", "attachment;filename=student.xls");

        //刷新缓冲
        response.flushBuffer();

        //workbook将Excel写入到response的输出流中，供页面下载
        workbook.write(response.getOutputStream());
    }


}
